import React from 'react';
import { Loader2, CheckCircle2, XCircle } from 'lucide-react';
import { RichContent } from './RichContent';
import { Skeleton } from '@/components/ui/skeleton';
import type { AnswerStatus } from '@/lib/langgraph-chat-ui';
import { useStreamdown, useStreamdownStatus } from '@/lib/streamdown';

interface AnswerCardProps {
  content: string;
  status: AnswerStatus;
  timestamp?: string;
}

function resolveStatusMeta(status: AnswerStatus) {
  switch (status) {
    case 'loading':
      return {
        icon: <Loader2 className="w-4 h-4 animate-spin" />,
        label: '模型正在生成...'
      };
    case 'complete':
      return {
        icon: <CheckCircle2 className="w-4 h-4 text-green-400" />,
        label: '生成完成'
      };
    case 'fail':
    default:
      return {
        icon: <XCircle className="w-4 h-4 text-red-400" />,
        label: '生成失败'
      };
  }
}

export function AnswerCard({ content, status, timestamp }: AnswerCardProps) {
  const targetContent = React.useMemo(() => {
    if (status === 'fail' && !content) {
      return '未获取到内容。';
    }
    if (!content && status === 'loading') {
      return '';
    }
    return content;
  }, [content, status]);

  const rendered = useStreamdown(targetContent);
  const typingState = useStreamdownStatus(rendered, targetContent);
  const showSkeleton = status === 'loading' && typingState.isEmpty;
  const statusInfo = resolveStatusMeta(status);

  const showMarkdown = !typingState.isTyping;

  return (
    <div className="bg-white/10 border border-white/20 rounded-2xl p-4 text-sm text-white space-y-3">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2 text-xs uppercase tracking-wide opacity-80">
          {statusInfo.icon}
          <span>{statusInfo.label}</span>
        </div>
        {timestamp && <span className="text-xs opacity-60">{timestamp}</span>}
      </div>

      {showSkeleton ? (
        <div className="space-y-2">
          <Skeleton height={14} />
          <Skeleton height={14} width="90%" />
          <Skeleton height={14} width="75%" />
        </div>
      ) : (
        <div className="max-h-[320px] overflow-auto pr-1">
          {showMarkdown ? (
            <RichContent content={rendered || targetContent} />
          ) : (
            <div className="typing-gradient whitespace-pre-wrap leading-relaxed">{rendered}</div>
          )}
        </div>
      )}
    </div>
  );
}
